﻿/*************************************************************************
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using NVelocity.App;
using NVelocity.Context;
using NVelocity;
using Castle.Components.Common.TemplateEngine.NVelocityTemplateEngine;
using System.Collections;
using CatchUpTv.Downloader.Australia.AbcIView;
using CatchUpTv.Downloader;
using System.Text.RegularExpressions;
using CatchUpTv.Tv;
using System.Threading;
using CatchUpTv.Downloader.Australia.Sbs;

namespace CatchUpTv.UI
{
    /// <summary>
    /// The main form for the UI.
    /// </summary>
    public partial class MainForm : Form
    {
        /// <summary>
        /// The template directory.
        /// </summary>
        string _templateDirectory;

        /// <summary>
        /// The home page URL.
        /// </summary>
        string _homePage;

        /// <summary>
        /// The downloads page URL.
        /// </summary>
        string _downloadsPage;

        /// <summary>
        /// The map of downloaders.
        /// </summary>
        IDictionary<string, IDownloader> _downloaders = new Dictionary<string, IDownloader>();

        IDictionary<string, object> _pageContextCache = new Dictionary<string, object>();

        public MainForm()
        {
            InitializeComponent();
            webBrowser.Navigating += webBrowser_Navigating;

            _templateDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Templates");

            var iView = new AbcIViewDownloader();
            _downloaders.Add(iView.Id, iView);

            var sbsAu = new SbsDownloader();
            _downloaders.Add(sbsAu.Id, sbsAu);

            _downloadsPage = Path.Combine(_templateDirectory, "downloads.html");
            _homePage = Path.Combine(_templateDirectory, "home.html");
            webBrowser.Navigate(_homePage);
        }

        void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            string outputFile = null;
            string templateFile = null;
            IDictionary context = new Hashtable();

            var fileName = Path.GetFileName(e.Url.LocalPath);

            if (DownloaderUrlRegex.Match(fileName).Success)
            {
                templateFile = "downloader-template.html.vm";
                string downloaderId = DownloaderUrlRegex.Match(fileName).Groups[1].Value;
                context["downloader"] = _downloaders[downloaderId];
                outputFile = Path.Combine(_templateDirectory, string.Format("downloader-{0}", downloaderId));
            }
            else if (ShowUrlRegex.Match(fileName).Success)
            {
                templateFile = "show-template.html.vm";
                string downloaderId = ShowUrlRegex.Match(fileName).Groups[1].Value;
                string showId = ShowUrlRegex.Match(fileName).Groups[2].Value;
                
                var downloader = _downloaders[downloaderId];
                var show = downloader.Shows.Value
                    .Where(s => s.Id.Equals(showId))
                    .First();

                context["downloader"] = downloader;
                context["show"] = show;

                outputFile = Path.Combine(_templateDirectory, string.Format("show-{0}-{1}", downloaderId, show.Id));
            }
            else if (DownloadEpisodeUrlRegex.Match(fileName).Success)
            {
                string downloaderId = DownloadEpisodeUrlRegex.Match(fileName).Groups[1].Value;
                string showName = DownloadEpisodeUrlRegex.Match(fileName).Groups[2].Value;
                string episodeId = DownloadEpisodeUrlRegex.Match(fileName).Groups[3].Value;

                var downloader = _downloaders[downloaderId];
                var show = downloader.Shows.Value
                    .Where(s => s.Id.Equals(showName))
                    .First();
                var episode = show.Episodes.Value
                    .Where(ep => ep.Id.Equals(episodeId))
                    .First();

                DownloadEpisode(downloader, episode);

                e.Cancel = true;
            }

            // If an output file is specified then it needs to be generated via a template.
            if (outputFile != null)
            {
                var engine = new NVelocityTemplateEngine(_templateDirectory);
                engine.BeginInit();
                
                try
                {
                    using (var writer = new StreamWriter(outputFile))
                    {
                        engine.Process(context, templateFile, writer);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        this,
                        "Error generating HTML from template: " + ex.Message, 
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
        }

        private void DownloadEpisode(IDownloader downloader, Episode episode)
        {
            var progressBar = new DownloadProgress();
            progressBar.Dock = DockStyle.Left;
            downloadsPanel.Controls.Add(progressBar);

            Thread downloaderThread = new Thread(new ThreadStart(delegate
            {
                var episodeDownloader = new EpisodeDownloader(downloader, episode, progressBar);
            }));

            downloaderThread.Start();            
        }

        /// <summary>
        /// Handles click on the home button.
        /// </summary>
        private void homeButton_Click(object sender, EventArgs e)
        {
            webBrowser.Navigate(_homePage);
        }

        /// <summary>
        /// Handles click on the back button.
        /// </summary>
        private void backButton_Click(object sender, EventArgs e)
        {
            webBrowser.GoBack();
        }

        /// <summary>
        /// Handles click on the forward button.
        /// </summary>
        private void forwardButton_Click(object sender, EventArgs e)
        {
            webBrowser.GoForward();
        }

        /// <summary>
        /// Handles click on the downloads button.
        /// </summary>
        private void downloadsButton_Click(object sender, EventArgs e)
        {
            webBrowser.Navigate(_downloadsPage);
        }

        /// <summary>
        /// The regular expression for matching the downloader URL.
        /// </summary>
        private static readonly Regex DownloaderUrlRegex = new Regex(@"downloader-([\w\d_]+)");

        /// <summary>
        /// The regular expression for matching the show URL.
        /// </summary>
        private static readonly Regex ShowUrlRegex = new Regex(@"show-([\w\d_]+)-([\w\d_]+)");

        /// <summary>
        /// The regular expression for matching the episode download URL.
        /// </summary>
        private static readonly Regex DownloadEpisodeUrlRegex = new Regex(@"download-([\w\d_]+)-([\w\d_]+)-([\w\d_]+)");
    }
}
